package com.sijibao.amap;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.yicai.sijibao.utl.BusProvider;

/**
 * lat 纬度
 * lon 经度
 * code  唯一标示
 * postion 位置
 * @author JiangLiangJun
 *
 */
public class AdressService extends Service {
	

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		double lat = intent.getDoubleExtra("lat",0);
		double lon = intent.getDoubleExtra("lon",0);
		String code = intent.getStringExtra("code");
		
		LatLonPoint point = new LatLonPoint(lat, lon);
		int postion = intent.getIntExtra("postion",0);
		
		search(point,code,postion);
		return Service.START_REDELIVER_INTENT;
	}
	
	
	
	public void search(LatLonPoint lp,final String code ,final int postion){
		GeocodeSearch geocoderSearch = new GeocodeSearch(getBaseContext()); 

		geocoderSearch.setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
			
			@Override
			public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
				// TODO Auto-generated method stub
				  if(rCode == 0){ 
				      
				        if(result != null&&result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress()!=null)
				                 { 

				        	GeoAddressEvent event = new GeoAddressEvent(code ,result.getRegeocodeAddress().getFormatAddress(),postion );

				            BusProvider.getInstance().post(event);

				        }else{ 

				        } 
				    }else{ 

				    }
				     
			}
			
			@Override
			public void onGeocodeSearched(GeocodeResult result, int rCode) {

				// TODO Auto-generated method stub
				
			}
		}); 	

		// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系   
		RegeocodeQuery query = new RegeocodeQuery(lp, 2000,GeocodeSearch.AMAP);
	
		geocoderSearch.getFromLocationAsyn(query);
	}
	
	/**
	 * 回传事件
	 * @author JiangLiangJun
	 *
	 */
	public static class GeoAddressEvent{
		
		public GeoAddressEvent(String code ,String address,int postion){
			this.code  =  code ;
			this.address  =  address ;
			this.postion  =  postion ;
		}
		public String code;
		public String address;
		public int postion;
		
	}

	
	

	
	
	
	

}
